import {
    defineAsyncComponent,
    h
} from 'vue'
import Loading from '../components/Loading.vue'
import ErrorCom from '../components/ErrorCom.vue'
import "nprogress/nprogress.css"
import NProgress from 'nprogress';

/**
 * 获取最小值和最大值中间的数
 * @param {number} min 最小值 
 * @param {number} max 最大值
 * @returns 最小值和最大值中间的数
 */
function random(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
}
/**
 * 返回一个promise延迟函数
 * @param { number } duration 延迟时间 
 * @returns 推向成功
 */
function delay(duration) {
    if (!duration) {
        duration = random(1000, 3000);
    }
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve()
        }, duration);
    })
}
export function asyncComponent(path) {
    return defineAsyncComponent({
        loader: async () => {
            await delay()
            if (Math.random() < 0.5) {
                return import(path)
            }
            throw new Error('组件加载失败')
        },
        loadingComponent: Loading,
        errorComponent: {
            render() {
                return h(ErrorCom, '组件加载失败');
            }
        },
    })
}


export function getAsyncPage(pathUrl) {
    return defineAsyncComponent({
        loader: async () => {
            NProgress.start();
            await delay();
            let resCom = import(pathUrl);
            NProgress.done();
            return resCom;

        },
        loadingComponent: Loading,
    })
    // return defineAsyncComponent(()=>import( path))
}
